package com.vipboot.framework.web.trace;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Slf4j
public class WebTraceFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        try {
            //如果有上层调用就用上层的ID
            String traceId = request.getHeader(MdcTraceUtil.TraceIdHeaderKey);
            String spanId = request.getHeader(MdcTraceUtil.SpanIdHeaderKey);
            if (StrUtil.isEmpty(traceId)) {
                MdcTraceUtil.addTrace();
            } else {
                MdcTraceUtil.putTrace(traceId, spanId);
            }
            log.info("TraceId:{},SpanId:{}", MdcTraceUtil.getTraceId(), MdcTraceUtil.getSpanId());
            response.setHeader(MdcTraceUtil.TraceIdHeaderKey, MdcTraceUtil.getTraceId());
            filterChain.doFilter(request, response);
        } finally {
            MdcTraceUtil.removeTrace();
        }

    }
}

